package com.xiaoshuidi.cloud.module.member.service.index;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.xiaoshuidi.cloud.framework.common.pojo.CommonResult;
import com.xiaoshuidi.cloud.module.member.controller.admin.index.vo.AppIndexConfigEntityVO;
import com.xiaoshuidi.cloud.module.member.controller.admin.index.vo.ResourceVo;
import com.xiaoshuidi.cloud.module.member.controller.admin.index.vo.SetAppIndexConfigVo;
import com.xiaoshuidi.cloud.module.member.pojo.index.AppIndexConfigEntity;
import com.xiaoshuidi.cloud.module.member.mapper.index.AppIndexPageConfigMapper;
import com.xiaoshuidi.cloud.module.member.enums.AppIndexPageItemEnum;
import com.xiaoshuidi.cloud.module.member.service.user.MemberUserService;
import com.xiaoshuidi.cloud.module.rooms.api.apartment.ApartmentApi;
import com.xiaoshuidi.cloud.module.rooms.api.apartment.vo.RecommendApartmentInfoRespVO;
import com.xiaoshuidi.cloud.module.system.api.user.AdminUserApi;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author Leo.Li
 * @version generator
 * @description apps首页配置service层
 * @date 2023-05-19 17:20:47
 */
@Service
@Slf4j
public class AppIndexPageConfigService {

    Logger logger = LoggerFactory.getLogger(AppIndexPageConfigService.class);
    @Resource
    AppIndexPageConfigMapper appIndexPageConfigMapper;
    @Resource
    ApartmentApi apartmentApi;

    @Resource
    MemberUserService memberUserService;

    @Resource
    AdminUserApi adminUserApi;

    public List<AppIndexConfigEntityVO> appIndexConfigList() {
        List<AppIndexConfigEntity> list = appIndexPageConfigMapper.selectAppIndexConfigList();
        List<AppIndexConfigEntityVO> result = new ArrayList<>();
        if (CollectionUtils.isEmpty(list)) {
            for (AppIndexPageItemEnum item : AppIndexPageItemEnum.values()) {
                AppIndexConfigEntityVO vo = new AppIndexConfigEntityVO();
                vo.setIndexId(item.getIndex());
                vo.setItemName(item.getItem());
                result.add(vo);
            }
        } else {
            Map<Integer, AppIndexConfigEntity> temp = list.stream().collect(Collectors.toMap(it -> it.getIndexId(), Function.identity()));
            for (AppIndexPageItemEnum item : AppIndexPageItemEnum.values()) {
                if (temp.containsKey(item.getIndex())) {
                    AppIndexConfigEntityVO vo = new AppIndexConfigEntityVO();
                    AppIndexConfigEntity appIndexConfigEntity = temp.get(item.getIndex());
                    BeanUtils.copyProperties(appIndexConfigEntity, vo);
                    try {
                        String nickname = adminUserApi.getUser(Long.valueOf(appIndexConfigEntity.getUpdater())).getData().getNickname();
                        vo.setUpdatorName(nickname);
                    } catch (Exception e) {
                        log.error("获取内部员工失败");
                    }
                    result.add(vo);
                } else {
                    AppIndexConfigEntityVO vo = new AppIndexConfigEntityVO();
                    vo.setIndexId(item.getIndex());
                    vo.setItemName(item.getItem());
                    result.add(vo);
                }
            }
            result.sort(Comparator.comparing(AppIndexConfigEntityVO::getIndexId));
        }
        return result;

    }

    public void resetAppIndexPageConfigs() {
        List<AppIndexConfigEntity> list = appIndexPageConfigMapper.selectAppIndexConfigList();
        if (!CollectionUtils.isEmpty(list)) {
            appIndexPageConfigMapper.deleteBatchIds(list.stream().map(it -> it.getId()).collect(Collectors.toList()));
        }
    }

    public void setAppIndexPageConfig(SetAppIndexConfigVo form) {
        AppIndexPageItemEnum enu = AppIndexPageItemEnum.getEnumByIndex(form.getIndexId());
        if (enu != null) {
            form.setItemName(enu.getItem());
        }
        if (form.getId() != null) {
            AppIndexConfigEntity entity = appIndexPageConfigMapper.selectById(form.getId());
            if (entity != null) {
                entity.setConfigJson(form.getConfigJson());
                appIndexPageConfigMapper.updateById(entity);
            } else {
                entity = new AppIndexConfigEntity();
                entity.setIndexId(form.getIndexId());
                entity.setItemName(AppIndexPageItemEnum.getEnumByIndex(form.getIndexId()).getItem());
                entity.setConfigJson(form.getConfigJson());
                appIndexPageConfigMapper.insert(entity);
            }
        } else {
            AppIndexConfigEntity entity = new AppIndexConfigEntity();
            entity.setIndexId(form.getIndexId());
            entity.setItemName(AppIndexPageItemEnum.getEnumByIndex(form.getIndexId()).getItem());
            entity.setConfigJson(form.getConfigJson());
            appIndexPageConfigMapper.insert(entity);
        }
    }

    /**
     * @param enu
     * @param lat         纬度
     * @param lon         经度
     * @param apartmentId 需要排除的门店
     * @return
     */
    public Object getAppIndexConfig(AppIndexPageItemEnum enu, String lat, String lon, Long apartmentId) {
        AppIndexConfigEntity entity = appIndexPageConfigMapper.getConfigByIndex(enu.getIndex());
        JSONObject vo = new JSONObject();
        if (entity != null) {
            //推荐房源要补充公寓信息、价格、电话
            if (enu.getIndex().equals(AppIndexPageItemEnum.RESOURCE.getIndex())) {
                ResourceVo temp = JSONObject.parseObject(entity.getConfigJson(), ResourceVo.class);
                List<ResourceVo.ResourceItemVo> items = temp.getItems();
                if (ObjectUtil.isNotEmpty(apartmentId)) {
                    items = items.stream().filter(p -> !p.getAptId().equals(apartmentId)).collect(Collectors.toList());
                    temp.setItems(items);
                }
                if (!CollectionUtils.isEmpty(items)) {
                    List<Long> ids = items.stream().map(it -> it.getAptId()).collect(Collectors.toList());
                    CommonResult<List<RecommendApartmentInfoRespVO>> result = apartmentApi.recommendApartmentInfo(ids, lat, lon);
                    if (result.getData() != null) {
                        Map<Long, RecommendApartmentInfoRespVO> map = result.getData().stream().collect(Collectors.toMap(it -> it.getApartmentId(), Function.identity()));
                        items.stream().forEach(it -> {
                            if (map.containsKey(it.getAptId())) {
                                RecommendApartmentInfoRespVO info = map.get(it.getAptId());
                                it.setAptName(info.getApartmentName());
                                it.setAddress(info.getAddress());
                                if (info.getPrice() != null) {
                                    it.setRent(BigDecimal.valueOf(info.getPrice()));
                                } else {
                                    it.setRent(null);
                                }
                                it.setPicUrl(info.getPicUrl());
                                it.setHotline(info.getStoreTel());
                                // 补充房型信息
                                List<ResourceVo.LayoutInfo> layoutInfos = new ArrayList<>();
                                for (RecommendApartmentInfoRespVO.LayoutInfo layoutInfo : info.getLayoutInfos()) {
                                    ResourceVo.LayoutInfo layout = new ResourceVo.LayoutInfo();
                                    BeanUtil.copyProperties(layoutInfo, layout);
                                    layoutInfos.add(layout);
                                }
                                it.setLayoutInfo(layoutInfos);
                                it.setDistance(info.getMeter());
                                it.setTags(StrUtil.isNotEmpty(info.getTags()) ? Arrays.asList(info.getTags().split(",")) : new ArrayList<String>());
                            }
                        });
                    }
                }
                return temp;
            } else {
                return JSONObject.parseObject(entity.getConfigJson());
            }
        }
        return vo;
    }
}
